package com.trkj.service;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;

import com.trkj.dao.EmpDAO;
import com.trkj.pojo.Emp;
import com.trkj.vo.HistoryTaskVo;

/**
 * 流程控制的service
 * 
 * @author Lixd
 *
 */
public class WorkFlowService {

	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private FormService formService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	EmpDAO empDAO;
	@Autowired
	ProcessEngine processEngine;
	@Autowired
	LoanService loanService;
	@Autowired
	QuitService quitService;
	@Autowired
	StandardService standardService;
	/**
	 * 根据流程id和流程名称获取最后一步的任务id
	 * @author Lixd
	 * @param processId
	 * @param processName
	 * @return
	 */
	public String getFinishedTaskIdByProcessIdAndProcessName(String processId,String processName){
		if (processName!=null && processId!=null) {
			String processDefinitionKey = "";
			switch (processName) {
			case "人员离职流程":
				processDefinitionKey="quit_act";
				break;
			case "人员转正流程":
				processDefinitionKey="standard_act";
				break;
			case "人员加班流程":
				processDefinitionKey="overwork_act";
				break;
			}
			HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery()
					.variableValueEquals("processid", processId)
					.processDefinitionKey(processDefinitionKey).singleResult();
			if (hpi!=null) {
				List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(hpi.getId())
							.orderByHistoricTaskInstanceEndTime().desc()
							.list();
				if (list!=null && list.size()>0) {
					return list.get(0).getId();
				}
			}
		}
		return null;
	}
	
	
	
	/**
	 * 得到所有已经完成的离职流程id
	 * 
	 * @author Lixd
	 * @return
	 */
	public List<String> getUnFinishedProcessIds(String processDefinitionKey,Integer empId) {
		List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery()
				.processDefinitionKey(processDefinitionKey)
				.variableValueEquals("writer", empId)
				.unfinished().list();
		List<String> processIdList = new ArrayList<>();
		for (HistoricProcessInstance hpi : list) {
			HistoricVariableInstance hvi = historyService.createHistoricVariableInstanceQuery()
					.processInstanceId(hpi.getId()).variableName("processid").singleResult();
			processIdList.add(String.valueOf(hvi.getValue()));
		}
		return processIdList;
	}
	
	/**
	 * 获得最近一次的流程编号
	 * @author Lixd
	 * @param empId 登录人id
	 * @param processDefinitionKey 流程定义的key
	 * @return
	 */
	public Integer getRecentlyProcess(Integer empId,String processDefinitionKey) {
		List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().variableValueEquals("writer", empId)
							.processDefinitionKey(processDefinitionKey).orderByProcessInstanceEndTime()
							.desc().list();
		System.out.println(list.size());
		if (list.size()>0) {
			HistoricProcessInstance hpi = list.get(0);
			HistoricVariableInstance hvi = historyService.createHistoricVariableInstanceQuery().processInstanceId(hpi.getId())
						.variableName("processid").singleResult();
			if (hvi!=null) {
				return Integer.valueOf(String.valueOf(hvi.getValue()));
			}
		}
		return null;
	}

	/**
	 * 通过部署id级联删除流程定义
	 * @author Lixd
	 * @param deploymentId
	 */
	public void deleteProcessDefinition(String deploymentId) {
		repositoryService.deleteDeployment(deploymentId, true);
	}

	/**
	 * 通过流程实例id查询流程定义名称
	 * 
	 * @author Lixd
	 * @param processInstenceId
	 * @return
	 */
	public String getProcessNameByProcessInstenceId(String processInstenceId) {
		HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
				.processInstanceId(processInstenceId).singleResult();
		if (processInstance != null) {
			String deploymentId = repositoryService.createProcessDefinitionQuery()
					.processDefinitionId(processInstance.getProcessDefinitionId()).singleResult().getDeploymentId();
			Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
			return deployment.getName();
		}
		return "";
	}

	/**
	 * 去完成有业务的任务
	 * 
	 * @author Lixd
	 * @param userId
	 * @param taskName
	 * @return
	 */
	public boolean toCompleteMyPersonalTask(String taskId, String empid, String ishandle, String comment) {
		try {
			String processid = getProcessIdByTaskId(taskId);
			String processName = getProcessName(taskId);
			boolean iscomplete = true;
			if ("人员借款流程".equals(processName)) {
				if ("已批账".equals(ishandle)) {
					iscomplete = loanService.saveLoanInfo(Integer.valueOf(processid));
				}
			}
			if ("人员离职流程".equals(processName)) {
				if ("已归档".equals(ishandle)) {
					System.out.println("离职成功");
					iscomplete = quitService.updateEmpstateInfo(Integer.valueOf(processid));
				
				}
			}
			if ("人员转正流程".equals(processName)) {
				if ("已归档".equals(ishandle)) {
					System.out.println("已经转正");
					iscomplete = standardService.updatestandardtime(Integer.valueOf(processid));
				}
			}
			if (iscomplete) {
				addComment(empid, taskId, "结论："+ishandle+ "\r\n批注信息：" + comment);
				return completeMyPersonalTask(taskId);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 通过任务id获取流程绑定的流程记录id
	 * 
	 * @author Lixd
	 * @param taskId
	 * @return
	 */
	public String getProcessIdByTaskId(String taskId) {
		if (taskId != null) {
			String processInstanceId = getProcessInstanceIdByTaskId(taskId);
			return String.valueOf(historyService.createHistoricVariableInstanceQuery()
					.processInstanceId(processInstanceId).variableName("processid").singleResult().getValue());
		}
		return null;
	}

	/**
	 * 通过任务id获取流程定义的名称
	 * 
	 * @author Lixd
	 * @param taskId
	 * @return
	 */
	public String getProcessName(String taskId) {
		HistoricTaskInstance histask = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
		if (histask != null) {
			String deploymentId = repositoryService.createProcessDefinitionQuery()
					.processDefinitionId(histask.getProcessDefinitionId()).singleResult().getDeploymentId();
			Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
			return deployment.getName();
		}
		return "";
	}

	/**
	 * 通过任务id得到任务名称
	 * @author Lixd
	 * @param taskId
	 * @return
	 */
	public String getTaskNameByID(String taskId) {
		if (taskId != null) {
			return historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult().getName();
		}
		return "";
	}

	/**
	 * 开始流程
	 * 
	 * @author Lixd
	 * @param processId
	 *            表单编号
	 * @param useid
	 *            写表单的人
	 * @param processDefinitionKey
	 *            流程的key
	 * @return
	 */
	public boolean startEmployProcess(Integer processId, Integer useid, String processDefinitionKey) {
		try {
			Map<String, Object> map = new HashMap<>();
			Emp emp = empDAO.findOne(useid);
			Emp superior = emp.getEmp();
			Emp personnerl;
			Emp manager = empDAO.findOneByPosition(4);
			Emp finance;
			switch (processDefinitionKey) {
			case "employ_act":
				personnerl = empDAO.findOneByPosition(7);
				map.put("deptboss", superior.getEmpId());
				map.put("processid", processId);
				map.put("writer", useid);
				map.put("boss", manager.getEmpId());
				map.put("personnel", personnerl.getEmpId());
				break;
			case "loan_act":
				finance = empDAO.findOneByPosition(8);
				map.put("deptboss", superior.getEmpId());
				map.put("processid", processId);
				map.put("writer", useid);
				map.put("boss", manager.getEmpId());
				map.put("finance", finance.getEmpId());
				break;
			case "quit_act":
				personnerl = empDAO.findOneByPosition(7);
				map.put("deptboss", superior.getEmpId());
				map.put("processid", processId);
				map.put("writer", useid);
				map.put("boss", manager.getEmpId());
				map.put("personnel", personnerl.getEmpId());
				break;
			case "standard_act":
				personnerl = empDAO.findOneByPosition(7);
				map.put("deptboss", superior.getEmpId());
				map.put("processid", processId);
				map.put("writer", useid);
				map.put("personnel", personnerl.getEmpId());
				break;
			case "overwork_act":
				personnerl = empDAO.findOneByPosition(7);
				map.put("deptboss", superior.getEmpId());
				map.put("processid", processId);
				map.put("writer", useid);
				map.put("personnel", personnerl.getEmpId());
				break;
			// case "employ_act":
			//
			// break;
			}
			return startProcess(useid, processDefinitionKey, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 查询我已经办理的流程
	 * @author Lixd
	 * @param useid
	 * @return
	 */
	public List<HistoricTaskInstance> findMyOriginalProcess(Integer useid) {
		List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().taskAssignee(useid + "")
				.finished().list();
		return list;
	}

	/**
	 * 给批注表单加载批注
	 * 
	 * @author Lixd
	 * @param taskId
	 *            当前任务Id
	 * @return
	 */
	public Map<String, Object> loadComments(String taskId) {
		List<Comment> allComments = getAllComments(taskId);
		String processInstanceId = getProcessInstanceIdByTaskId(taskId);
		List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
				.processInstanceId(processInstanceId).list();
		Map<String, Object> map = new HashMap<>();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		for (HistoricTaskInstance hti : list) {
			String taskName = hti.getName();
			Integer empId = Integer.valueOf(hti.getAssignee());
			String histaskId = hti.getId();
			Comment mycomment = null;
			if ("部门主管签字".equals(taskName)) {
				for (Comment comment : allComments) {
					if (comment.getTaskId().equals(histaskId)) {
						mycomment = comment;
						break;
					}
				}
				if (mycomment != null) {
					String empName = empDAO.findOne(Integer.valueOf(mycomment.getUserId())).getEmpName();
					String value = mycomment.getFullMessage()+ "\r\n办理人：" + empName + "\r\n办理时间：" + sf.format(mycomment.getTime());
					map.put("deptBoss", value);
				}
			} else if ("总经理签字".equals(taskName)) {
				for (Comment comment : allComments) {
					if (comment.getTaskId().equals(histaskId)) {
						mycomment = comment;
						break;
					}
				}
				if (mycomment != null) {
					String empName = empDAO.findOne(Integer.valueOf(mycomment.getUserId())).getEmpName();
					String value = mycomment.getFullMessage()+ "\r\n办理人：" + empName + "\r\n办理时间：" + sf.format(mycomment.getTime());
					map.put("zongBoss", value);
				}
			} else if ("人事归档".equals(taskName)) {
				for (Comment comment : allComments) {
					if (comment.getTaskId().equals(histaskId)) {
						mycomment = comment;
						break;
					}
				}
				if (mycomment != null) {
					String empName = empDAO.findOne(Integer.valueOf(mycomment.getUserId())).getEmpName();
					String value = mycomment.getFullMessage()+ "\r\n办理人：" + empName + "\r\n办理时间：" + sf.format(mycomment.getTime());
					map.put("personnel", value);
				}
			} else if ("财务部批账".equals(taskName)) {
				for (Comment comment : allComments) {
					if (comment.getTaskId().equals(histaskId)) {
						mycomment = comment;
						break;
					}
				}
				if (mycomment != null) {
					String empName = empDAO.findOne(Integer.valueOf(mycomment.getUserId())).getEmpName();
					String value = mycomment.getFullMessage()+ "\r\n办理人：" + empName + "\r\n办理时间：" + sf.format(mycomment.getTime());
					map.put("finance", value);
				}
			}
		}
		return map;
	}

	/**
	 * 查询当前流程的所有任务信息
	 * 
	 * @author Lixd
	 * @param taskId
	 *            任务id
	 * @return
	 */
	public List<HistoryTaskVo> findAllAssignee(String taskId) {
		String processInstanceId = getProcessInstanceIdByTaskId(taskId);
		List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
				.processInstanceId(processInstanceId).list();
		List<HistoryTaskVo> htvlist = new ArrayList<>();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		for (HistoricTaskInstance hti : list) {
			HistoryTaskVo htv = new HistoryTaskVo();
			Emp emp = empDAO.findOne(Integer.valueOf(hti.getAssignee()));
			htv.setTaskName(hti.getName());
			htv.setAssignee(emp.getEmpName());
			if (hti.getEndTime() != null) {
				htv.setEndTime(sf.format(hti.getEndTime()));
			}
			htv.setStartTime(sf.format(hti.getStartTime()));
			if (hti.getEndTime() != null) {
				htv.setTaskState("完成");
			} else if (hti.getStartTime() != null && hti.getEndTime() == null) {
				htv.setTaskState("进行中");
			}
			htvlist.add(htv);
		}
		return htvlist;
	}

	/**
	 * 获得当前任务的流程实例id
	 * 
	 * @author Lixd
	 * @param taskId
	 *            当前任务id
	 * @return
	 */
	public String getProcessInstanceIdByTaskId(String taskId) {
		return historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult().getProcessInstanceId();
	}

	/**
	 * 通过当前任务id查询历史任务的批注
	 * @author Lixd
	 * @param taskId
	 *            当前任务id
	 * @return
	 */
	public List<Comment> getAllComments(String taskId) {
		List<Comment> list = new ArrayList<>();
		String processInstanceId = getProcessInstanceIdByTaskId(taskId);
		List<HistoricTaskInstance> hislist = historyService.createHistoricTaskInstanceQuery()
				.processInstanceId(processInstanceId).list();
		if (hislist != null && hislist.size() > 0) {
			for (HistoricTaskInstance histask : hislist) {
				String id = histask.getId();
				List<Comment> taskComments = taskService.getTaskComments(id);
				list.addAll(taskComments);
			}
		}
		return list;
	}

	/**
	 * 完成任务时添加一个批注信息，并制定任务完成人
	 * @author Lixd
	 * @param empid
	 *            登录后存入Session中的empid
	 * @param taskId
	 *            任务编号
	 * @param message
	 *            要保存的批注
	 * @return
	 */
	public Comment addComment(String empid, String taskId, String message) {
		Authentication.setAuthenticatedUserId(empid);
		String processInstanceId = getProcessInstanceIdByTaskId(taskId);
		return taskService.addComment(taskId, processInstanceId, message);
	}

	/**
	 * 查询流程图
	 * @author Lixd
	 * @param request
	 * @param response
	 * @param pId
	 *            流程实例编号
	 * @throws IOException
	 */
	public void queryProPlan(HttpServletRequest request, HttpServletResponse response, String processInstanceId)
			throws IOException {
		// 获取历史流程实例
		HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
				.processInstanceId(processInstanceId).singleResult();
		// 获取流程图
		BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
		ProcessEngineConfiguration processEngineConfiguration = processEngine.getProcessEngineConfiguration();
		Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);

		ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
		ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity) repositoryService
				.getProcessDefinition(processInstance.getProcessDefinitionId());

		List<HistoricActivityInstance> highLightedActivitList = historyService.createHistoricActivityInstanceQuery()
				.processInstanceId(processInstanceId).list();
		// 高亮环节id集合
		List<String> highLightedActivitis = new ArrayList<String>();

		// 高亮线路id集合
		List<String> highLightedFlows = getHighLightedFlows(definitionEntity, highLightedActivitList);

		for (HistoricActivityInstance tempActivity : highLightedActivitList) {
			String activityId = tempActivity.getActivityId();
			highLightedActivitis.add(activityId);
		}

		// 中文显示的是口口口，设置字体就好了
		InputStream imageStream = diagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivitis,
				highLightedFlows, "宋体", "宋体", null, 1.0);
		// 单独返回流程图，不高亮显示
		// InputStream imageStream = diagramGenerator.generatePngDiagram(bpmnModel);
		// 输出资源内容到相应对象
		byte[] b = new byte[1024];
		int len;
		while ((len = imageStream.read(b, 0, 1024)) != -1) {
			response.getOutputStream().write(b, 0, len);
		}

	}

	/**
	 * 获取需要高亮的线
	 * @author Lixd
	 * @param processDefinitionEntity
	 * @param historicActivityInstances
	 * @return
	 */
	private List<String> getHighLightedFlows(ProcessDefinitionEntity processDefinitionEntity,
			List<HistoricActivityInstance> historicActivityInstances) {

		List<String> highFlows = new ArrayList<String>();// 用以保存高亮的线flowId
		for (int i = 0; i < historicActivityInstances.size() - 1; i++) {// 对历史流程节点进行遍历
			ActivityImpl activityImpl = processDefinitionEntity
					.findActivity(historicActivityInstances.get(i).getActivityId());// 得到节点定义的详细信息
			List<ActivityImpl> sameStartTimeNodes = new ArrayList<ActivityImpl>();// 用以保存后需开始时间相同的节点
			ActivityImpl sameActivityImpl1 = processDefinitionEntity
					.findActivity(historicActivityInstances.get(i + 1).getActivityId());
			// 将后面第一个节点放在时间相同节点的集合里
			sameStartTimeNodes.add(sameActivityImpl1);
			for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
				HistoricActivityInstance activityImpl1 = historicActivityInstances.get(j);// 后续第一个节点
				HistoricActivityInstance activityImpl2 = historicActivityInstances.get(j + 1);// 后续第二个节点
				if (activityImpl1.getStartTime().equals(activityImpl2.getStartTime())) {
					// 如果第一个节点和第二个节点开始时间相同保存
					ActivityImpl sameActivityImpl2 = processDefinitionEntity
							.findActivity(activityImpl2.getActivityId());
					sameStartTimeNodes.add(sameActivityImpl2);
				} else {
					// 有不相同跳出循环
					break;
				}
			}
			List<PvmTransition> pvmTransitions = activityImpl.getOutgoingTransitions();// 取出节点的所有出去的线
			for (PvmTransition pvmTransition : pvmTransitions) {
				// 对所有的线进行遍历
				ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition.getDestination();
				// 如果取出的线的目标节点存在时间相同的节点里，保存该线的id，进行高亮显示
				if (sameStartTimeNodes.contains(pvmActivityImpl)) {
					highFlows.add(pvmTransition.getId());
				}
			}
		}
		return highFlows;
	}

	/**
	 * 判断流程是否已经结束
	 * 
	 * @author Lixd
	 * @param processInstanceId
	 *            流程实例ID
	 * @return true 结束，false 未结束
	 */
	public boolean isFinished(String processInstanceId) {
		return historyService.createHistoricProcessInstanceQuery().finished().processInstanceId(processInstanceId)
				.count() > 0;
	}

	/**
	 * 部署流程定义（从classpath）
	 * 
	 * @author Lixd
	 */
	public void deploymentProcessDefinition_classpath(String processName, String bpmnPath, String pngPath) {
		Deployment deployment = repositoryService.createDeployment()// 创建一个部署对象//与流程定义和部署对象相关的Service
				.name(processName)// 添加部署的名称
				.addClasspathResource(bpmnPath)// 从classpath的资源中加载，一次只能加载一个文件
				.addClasspathResource(pngPath)// 从classpath的资源中加载，一次只能加载一个文件
				.deploy();// 完成部署
	}

	/**
	 * 绑定表单并启动流程
	 * 
	 * @author Lixd
	 * @param processId
	 *            表单记录编号
	 * @param useid
	 * @param processDefinitionKey
	 *            流程定义的KEY，bpmn的ID
	 */
	public boolean startProcess(Integer useid, String processDefinitionKey, Map<String, Object> map) {
		try {
			ProcessInstance pi = runtimeService// 与正在执行的流程实例和执行对象相关的Service
					.startProcessInstanceByKey(processDefinitionKey, map);// 使用流程定义的key启动流程实例，key对应helloworld.bpmn文件中id的属性值，使用key值启动，默认是按照最新版本的流程定义启动
			String id = taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult()
					.getId();
			return completeMyPersonalTask(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 完成我的任务
	 * 
	 * @author Lixd
	 * @param taskid
	 * @return
	 */
	public boolean completeMyPersonalTask(String taskid) {
		try {
			taskService.complete(taskid);
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 分页查询个人所有任务
	 * 
	 * @author Lixd
	 * @param useid
	 * @param firstResult
	 *            第一条
	 * @param maxResults
	 *            页大小
	 * @return
	 */
	public List<Task> findMyPersonalTask(Integer useid, int firstResult, int maxResults) {
		String assignee = useid + "";
		List<Task> list = taskService// 与正在执行的任务管理相关的Service
				.createTaskQuery()// 创建任务查询对象
				.taskAssignee(assignee)// 指定个人任务查询，指定办理人
				.orderByTaskCreateTime().asc()// 使用创建时间的升序排列
				.listPage(firstResult, maxResults);// 分页查询
		return list;
	}

	/**
	 * 不分页查询所有任务
	 * 
	 * @author Lixd
	 * @param useid
	 * @return
	 */
	public List<Task> findMyPersonalTask(Integer useid) {
		String assignee = useid + "";
		List<Task> list = taskService// 与正在执行的任务管理相关的Service
				.createTaskQuery()// 创建任务查询对象
				.taskAssignee(assignee)// 指定个人任务查询，指定办理人
				.orderByTaskCreateTime().asc()// 使用创建时间的升序排列
				// .listPage(firstResult, maxResults);//分页查询
				.list();// 返回列表
		return list;
	}

	public void setHistoryService(HistoryService historyService) {
		this.historyService = historyService;
	}

	public void setFormService(FormService formService) {
		this.formService = formService;
	}

	public void setRuntimeService(RuntimeService runtimeService) {
		this.runtimeService = runtimeService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public void setRepositoryService(RepositoryService repositoryService) {
		this.repositoryService = repositoryService;
	}


	/**
	 * 得到所有已经完成的离职流程id
	 * 
	 * @author Lixd
	 * @return
	 */
	public List<String> getFinishedQuitProcessIds() {
		List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery()
				.deploymentId("quit_act:1:17504").finished().list();
		List<String> processIdList = new ArrayList<>();
		for (HistoricProcessInstance hpi : list) {
			HistoricVariableInstance hvi = historyService.createHistoricVariableInstanceQuery()
					.processInstanceId(hpi.getId()).variableName("processid").singleResult();
			processIdList.add(String.valueOf(hvi.getValue()));
		}
		return processIdList;
	}
	
	
	/**
	 * 获得最近一次的流程编号
	 * @author Lixd
	 * @param empId 登录人id
	 * @param processDefinitionKey 流程定义的key
	 * @return
	 */
	public Integer getRecentlyProcessFinished(Integer empId,String processDefinitionKey) {
		List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().variableValueEquals("writer", empId)
							.processDefinitionKey(processDefinitionKey).orderByProcessInstanceEndTime().finished()
							.desc().list();
		System.out.println(list.size());
		if (list.size()>0) {
			HistoricProcessInstance hpi = list.get(0);
			HistoricVariableInstance hvi = historyService.createHistoricVariableInstanceQuery().processInstanceId(hpi.getId())
						.variableName("processid").singleResult();
			if (hvi!=null) {
				return Integer.valueOf(String.valueOf(hvi.getValue()));
			}
		}
		return null;
	}
	

}
